<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexSystemMsgRequest;
use App\Http\Requests\StoreSystemMsgRequest;
use App\Http\Requests\UpdateSystemMsgRequest;
use App\Http\Resources\SystemMsgResource;
use App\Models\SystemMsg;

class SystemMsgController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexSystemMsgRequest $request)
    {
        $signconfig = SystemMsg::query();

        $signconfig->when($request->filled('title'), function ($query) use ($request) {
            $title = $request->input('title');
            return $query->where('title', $title);
        });

        $data = $signconfig->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response = SystemMsgResource::collection($data);
        $total = $response->total(); // 获取分页信息中的总数
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreSystemMsgRequest $request, SystemMsg $systemMsg)
    {
        $systemMsg->fill($request->input());
        $systemMsg->save();
        return $this->success('添加成功', $systemMsg);
    }

    /**
     * Display the specified resource.
     */
    public function show(SystemMsg $systemMsg, $id)
    {
        $systemMsg = $systemMsg->findOrFail($id);
        $this->authorize('viewAny', $systemMsg);
        $data = new SystemMsgResource($systemMsg);
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(SystemMsg $systemMsg)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateSystemMsgRequest $request, SystemMsg $systemMsg, $id)
    {
        $systemMsg = $systemMsg->findOrFail($id);
        $systemMsg->fill($request->input());
        $systemMsg->save();
        return $this->success('添加成功', $systemMsg);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SystemMsg $systemMsg, $id)
    {
        $systemMsg = $systemMsg->findOrFail($id);
        $this->authorize('delete', $systemMsg);
        $systemMsg->delete();
        return $this->success('删除成功', $systemMsg);
    }
}
